﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.Windows.Input;
using Caliburn.Micro;
using CaliburnWpf.ViewModels.Infrastructure;
using CaliburnWpf.Views.Infrastructure;
using System.Collections;
using System.Collections.Specialized;

namespace MoneyManagerNET.Presentation.ViewModel.Base
{
    //for list based windows
    //Model property returns currently selected (may be this is not right)
    public class ListViewModel<T> : Conductor<T>.Collection.OneActive  where T :class  {

        public ListViewModel(IEnumerable<T> source)
        {
            Items.AddRange(source);
            this.PropertyChanged += (o, e) => { if (e.PropertyName == "ActiveItem")Moved();};
            CollectionViewSource.GetDefaultView(Items).CurrentChanged += (a, b) => { this.ActivateItem((T)(a as CollectionView).CurrentItem); };
        }

        public bool CanDelete { get { return ActiveItem != null; } }
        internal void Delete()
        {
            int idx = this.Items.IndexOf(ActiveItem);
            this.Items.Remove(ActiveItem);
            App.Storage.Delete(ActiveItem);

            if (idx < Items.Count)
                ActiveItem = Items[idx];
            else
                ActiveItem = null;

            RefreshCommandStatuses();
        } 

        protected virtual void RefreshCommandStatuses()
        {
            this.NotifyOfPropertyChange(()=>CanDelete);
        }


        protected virtual void Moved()
        {
            RefreshCommandStatuses();
        }


        public Hashtable identityMap {get{return WrapConverter.s_identityMap;}}

        protected void RaisePropertyChanged(object item, string p)
        {
            var notifyable =identityMap[item] as INotifyable;
            if (notifyable != null)
                notifyable.OnChange(p);
        }


        public void RaiseCollectionChanged(object iCollection)
        {
            var notifyable = (identityMap[iCollection] as INotifyableCollection);
            if (notifyable != null)
                notifyable.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
        }

    }
}
